<template>
  <div class="post-detail-container">
    <div class="header">
      <div class="back-btn" @click="goBack">
        <i class="fas fa-arrow-left"></i> 返回
      </div>
    </div>

    <div v-if="loading" class="loading">
      <i class="fas fa-spinner fa-spin"></i>
      <p>正在加载帖子内容...</p>
    </div>

    <div v-else-if="error" class="error">
      <i class="fas fa-exclamation-circle"></i>
      <p>{{ error }}</p>
      <button class="refresh-btn" @click="fetchPostData">重新加载</button>
    </div>

    <div v-else class="card post-detail-card">
      <div class="post-header">
        <div class="post-avatar">
          <van-image @click="jumpChat(postData.user.userId)" v-if="postData.user.avatar" round width="45" height="45" :src="postData.user.avatar" />
        </div>
        <div class="post-user-info">
          <div class="post-user-name">{{ postData.user.nickname }}</div>
          <div class="post-time">{{ formatTime(postData.createAt) }}</div>
        </div>
      </div>
      <div class="post-title">{{ postData.title }}</div>
      <div class="post-content">
        <p v-for="(paragraph, index) in postData.content.split('\\n')" :key="index">{{ paragraph }}</p>
        <!-- 图片展示区域 -->
        <div class="image-gallery" v-if="parsedImages && parsedImages.length > 0">
          <div
              class="image-item"
              v-for="(image, index) in parsedImages"
              :key="index"
          >
            <van-image @click="showImagePreview(index)" v-if="image" :src="image" class="gallery-image"/>
          </div>
        </div>
      </div>

      <div class="post-footer">
        <div class="post-action like" @click="handleAction('like')">
          <i :class="['fas', postData.isLiked ? 'fa-heart liked' : 'fa-heart']"></i>
          <span>{{ postData.likeCount }}</span>
        </div>
        <div class="post-action comment">
          <i class="fas fa-comment-dots"></i>
          <span>{{ postData.replyCount }}</span>
        </div>
        <div class="post-action collect" @click="handleAction('collect')">
          <i :class="['fas', postData.isCollected ? 'fa-star star' : 'fa-star']"></i>
          <span>{{ postData.collectCount }}</span>
        </div>
      </div>
    </div>

    <div v-if="!loading && !error" class="comments-section">
      <div class="section-title"><i class="fas fa-comments"></i> 评论 ({{ postData.replyCount }})</div>

      <div v-if="commentSuccess" class="success-message">
        <i class="fas fa-check-circle"></i> 评论发布成功！
      </div>

      <div class="comment-form">
        <input
            type="text"
            class="comment-input"
            placeholder="写下你的评论..."
            v-model="newComment.content"
            @keyup.enter="addComment"
        >
        <button
            class="comment-submit"
            @click="addComment"
            :disabled="commentLoading"
        >
          <span v-if="!commentLoading">发布</span>
          <span v-else>提交中...</span>
        </button>
      </div>

      <div class="comment-list">
        <div
            class="comment-item"
            v-for="(comment, index) in mainComments"
            :key="comment.id || index"
        >
          <div class="comment-avatar">
            <van-image @click="jumpChat(comment.user.userId)" round width="45" height="45" :src="comment.user.avatar" />
          </div>
          <div class="comment-content">
            <div class="comment-header">
              <div class="comment-author">{{ comment.user.nickname }}</div>
              <div class="comment-time">{{ formatTime(comment.createdAt) }}</div>
            </div>
            <div class="comment-text">{{ comment.content }}</div>
            <div class="comment-actions">
              <div class="comment-action" @click="toggleCommentLike(index)">
                <i :class="['far', comment.liked ? 'fa-heart liked' : 'fa-heart']"></i>
                <span>{{ comment.likeCount || 0 }}</span>
              </div>
              <div class="comment-action" @click="toggleReplyForm(index)">
                <i class="fas fa-reply"></i>
                <span>回复</span>
              </div>
            </div>

            <!-- 楼中楼回复表单 -->
            <div class="reply-form" v-if="comment.showReplyForm">
              <input
                  type="text"
                  class="reply-input"
                  placeholder="写下你的回复..."
                  v-model="comment.replyContent"
                  @keyup.enter="addReply(index)"
              >
              <button class="reply-submit" @click="addReply(index)">发送</button>
            </div>

            <!-- 楼中楼评论列表 -->
            <div class="nested-comments" v-if="replies[comment.commentId] && replies[comment.commentId].length">
              <div class="nested-comment-item" v-for="(reply, replyIndex) in replies[comment.commentId]" :key="replyIndex">
                <van-image round width="35" height="35" :src="reply.user.avatar" class="nested-comment-avatar" />
                <div class="nested-comment-content">
                  <div class="nested-comment-header">
                    <div class="nested-comment-author">{{ reply.user.nickname }}</div>
                    <div class="nested-comment-time">{{ formatTime(reply.createdAt) }}</div>
                  </div>
                  <div class="nested-comment-text">{{ reply.content }}</div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 图片放大预览层 -->
    <div v-if="showPreview" class="image-preview-overlay" @click="hideImagePreview">
      <div class="preview-container">
        <img
            :src="previewImage"
            class="preview-image"
            @click="hideImagePreview"
        >
        <div class="preview-nav" v-if="parsedImages.length > 1">
          <button class="nav-btn prev" @click.stop="showPrevImage" :disabled="currentImageIndex <= 0">
            <i class="fas fa-chevron-left"></i>
          </button>
          <button class="nav-btn next" @click.stop="showNextImage" :disabled="currentImageIndex >= parsedImages.length - 1">
            <i class="fas fa-chevron-right"></i>
          </button>
        </div>
        <div class="preview-count" v-if="parsedImages.length > 1">
          {{ currentImageIndex + 1 }} / {{ parsedImages.length }}
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, reactive, onMounted,computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import axios from '@/utils/axios';
import { showToast } from 'vant';

export default {
  name: 'PostDetail',
  setup() {
    const loading = ref(true);
    const error = ref(null);
    const postData = ref({
      user: {
        avatar: "",
        nickname: ""
      },
      createAt: "",
      title: "",
      content: "",
      isLiked: false,
      likeCount: 0,
      replyCount: 0,
      isCollected: false,
      collectCount: 0
    });

    // 定义评论相关的响应式变量
    const mainComments = ref([]);
    const replies = ref([]);
    const commentLoading = ref(false);
    const commentSuccess = ref(false);

    const route = useRoute();
    const router = useRouter();

    const newComment = reactive({
      content: '',
      postId: route.params.id,
    });

    // 时间格式化函数
    const formatTime = (timeStr) => {
      if (!timeStr) return '';

      // 创建Date对象
      const date = new Date(timeStr);

      // 检查日期是否有效
      if (isNaN(date.getTime())) {
        return timeStr;
      }

      // 转换为东八区时间 (UTC+8)
      const utcTime = date.getTime();
      const localOffset = date.getTimezoneOffset() * 60000; // 本地时区偏移(毫秒)
      const utc8Offset = 8 * 60 * 60 * 1000; // 东八区偏移(毫秒)
      const beijingTime = new Date(utcTime + localOffset + utc8Offset);

      // 计算与当前时间的时间差
      const now = new Date();
      const diffInSeconds = Math.floor((now - beijingTime) / 1000);

      // 如果是未来时间，直接显示格式化的日期
      if (diffInSeconds < 0) {
        return beijingTime.toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit'
        });
      }

      // 根据时间差显示相对时间
      if (diffInSeconds < 60) {
        return '刚刚';
      } else if (diffInSeconds < 3600) {
        return `${Math.floor(diffInSeconds / 60)}分钟前`;
      } else if (diffInSeconds < 86400) {
        return `${Math.floor(diffInSeconds / 3600)}小时前`;
      } else if (diffInSeconds < 2592000) {
        return `${Math.floor(diffInSeconds / 86400)}天前`;
      } else {
        return beijingTime.toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit'
        });
      }
    };

    const fetchPostData = async () => {
      loading.value = true;
      error.value = null;

      try {
        const [postResp, commentsResp] = await Promise.all([
          axios.get(`/api/posts/${route.params.id}`),
          axios.get(`/api/comments/${route.params.id}`),
        ]);

        postData.value = postResp.data;
        console.log(postResp)
        console.log(commentsResp)
        // 处理评论数据
        if (commentsResp.data && commentsResp.code === 200) {
          const commentsData = commentsResp.data;

          // 设置主评论
          mainComments.value = commentsData.mainComments || [];

          // 设置回复Map
          replies.value = commentsData.replies;
          console.log(replies.value)
          // 为每个主评论添加UI状态
          mainComments.value.forEach(comment => {
            comment.showReplyForm = false;
            comment.replyContent = '';
            comment.liked = false;
            comment.likeCount = comment.likeCount || 0;
          });
        }
      } catch (err) {
        error.value = '获取帖子数据失败，请稍后重试';
        console.error('Failed to fetch post data:', err);
      } finally {
        loading.value = false;
      }
    };

    const handleAction = async (type) => {
      if (!postData.value) return;

      const post = postData.value;
      const isActioned = type === 'like' ? post.isLiked : post.isCollected;
      const countKey = type === 'like' ? 'likeCount' : 'collectCount';
      const stateKey = type === 'like' ? 'isLiked' : 'isCollected';
      const successMsg = type === 'like' ? '点赞成功' : '收藏成功';
      const cancelMsg = type === 'like' ? '已取消点赞' : '已取消收藏';
      // 乐观UI更新
      const wasActioned = isActioned;
      post[stateKey] = !wasActioned;
      post[countKey] += wasActioned ? -1 : 1;

      try {
        const response = await axios.post(`/api/posts/${post.postId}/${type}`, {
          action: !wasActioned,
        });
        if (response.code !== 200) {
          // 如果API调用失败，回滚UI
          post[stateKey] = wasActioned;
          post[countKey] += wasActioned ? 1 : -1;
          showToast(response.msg || '操作失败');
          return;
        }
        // 根据API响应更新最终状态
        post[stateKey] = response.data;
        showToast(post[stateKey] ? successMsg : cancelMsg);
      } catch (error) {
        // 回滚UI
        post[stateKey] = wasActioned;
        post[countKey] += wasActioned ? 1 : -1;
        showToast('操作失败，请重试');
        console.error(`${type} operation failed:`, error);
      }
    };

    const addComment = async () => {
      if (!newComment.content.trim()) {
        showToast('评论内容不能为空');
        return;
      }
      commentLoading.value = true;

      try {
        const response = await axios.post(`/api/posts/${newComment.postId}/comments`, newComment);
        if (response.code !== 200) {
          showToast(response.msg || '发布评论失败');
          return;
        }
        // 更新本地评论列表和帖子回复计数
        mainComments.value.unshift({
          ...response.data,
          showReplyForm: false,
          replyContent: '',
          isNew: true
        });
        postData.value.replyCount += 1;
        newComment.content = ''; // 清空输入框
        commentSuccess.value = true;
        setTimeout(() => {
          commentSuccess.value = false;
        }, 3000);
        showToast('评论发布成功');
        window.location.reload();
      } catch (error) {
        showToast('发布评论失败，请重试');
        console.error('Add comment failed:', error);
      } finally {
        commentLoading.value = false;
      }
    };

    const toggleCommentLike = (index) => {
      const comment = mainComments.value[index];
      comment.liked = !comment.liked;
      comment.likeCount += comment.liked ? 1 : -1;
    };

    // 切换回复表单显示
    const toggleReplyForm = (index) => {
      mainComments.value[index].showReplyForm = !mainComments.value[index].showReplyForm;
      if (mainComments.value[index].showReplyForm) {
        // 隐藏其他评论的回复表单
        mainComments.value.forEach((item, i) => {
          if (i !== index && item.showReplyForm) {
            item.showReplyForm = false;
          }
        });
      }
    };

    // 添加楼中楼回复
    const addReply = async (index) => {
      const comment = mainComments.value[index];
      if (!comment.replyContent.trim()) {
        showToast('回复内容不能为空');
        return;
      }

      try {
        // 调用API添加回复
        const response = await axios.post(`/api/comments/${comment.commentId}/replies`, {
          postId: route.params.id,
          content: comment.replyContent,
          fatherCommentId: comment.id
        });

        if (response.code !== 200) {
          showToast(response.msg || '回复失败');
          return;
        }

        // 添加回复到当前评论的replies数组中
        if (!replies.value[comment.id]) {
          replies.value[comment.id] = [];
        }
        replies.value[comment.id].push(response.data);
        comment.replyContent = '';
        comment.showReplyForm = false;

        // 更新帖子回复计数
        postData.value.replyCount += 1;

        showToast('回复成功');
        window.location.reload();
      } catch (error) {
        showToast('回复失败，请重试');
        console.error('Add reply failed:', error);
      }
    };

    const goBack = () => {
      router.back();
    };

    onMounted(() => {
      fetchPostData();
    });
    // 图片预览相关状态
    const showPreview = ref(false);
    const previewImage = ref("");
    const currentImageIndex = ref(0);

    // 解析images字符串为数组
    const parsedImages = computed(() => {
      try {
        if (postData.value.images && typeof postData.value.images === 'string') {
          return JSON.parse(postData.value.images);
        }
        return [];
      } catch (e) {
        console.error('解析图片数据失败:', e);
        return [];
      }
    });

    // 显示图片预览
    const showImagePreview = (index) => {
      currentImageIndex.value = index;
      previewImage.value = parsedImages.value[index];
      showPreview.value = true;
      document.body.style.overflow = 'hidden'; // 防止背景滚动
    };

    // 隐藏图片预览
    const hideImagePreview = () => {
      showPreview.value = false;
      document.body.style.overflow = ''; // 恢复背景滚动
    };

    // 显示下一张图片
    const showNextImage = () => {
      currentImageIndex.value = (currentImageIndex.value + 1) % parsedImages.value.length;
      previewImage.value = parsedImages.value[currentImageIndex.value];
    };

    // 显示上一张图片
    const showPrevImage = () => {
      currentImageIndex.value = (currentImageIndex.value - 1 + parsedImages.value.length) % parsedImages.value.length;
      previewImage.value = parsedImages.value[currentImageIndex.value];
    };

    const jumpChat = (userId) => {
      router.push(`/chat/${userId}`);
    }


    return {
      loading,
      error,
      postData,
      mainComments,
      replies,
      commentLoading,
      commentSuccess,
      newComment,
      fetchPostData,
      handleAction,
      addComment,
      toggleCommentLike,
      toggleReplyForm,
      addReply,
      goBack,
      jumpChat,
      formatTime,
      parsedImages,
      showPreview,
      previewImage,
      currentImageIndex,
      showImagePreview,
      hideImagePreview,
      showNextImage,
      showPrevImage,
    };
  }
};
</script>

<style scoped>
.post-detail-container {
  min-height: 100vh;
  background-color: var(--background);
}

.header {
  position: sticky;
  top: 0;
  z-index: 10;
  display: flex;
  align-items: center;
  padding: 15px;
  background-color: var(--background);
}

.back-btn {
  font-size: 1.1rem;
  color: var(--text-dark);
  cursor: pointer;
}

.back-btn .fas {
  margin-right: 8px;
}

.loading,
.error {
  text-align: center;
  padding: 40px 0;
  color: var(--text-light);
}

.loading .fas,
.error .fas {
  font-size: 2.5rem;
  margin-bottom: 10px;
  color: #c9c9c9;
}

.loading .fas {
  animation: spin 1s linear infinite;
}

.error .refresh-btn {
  margin-top: 20px;
  padding: 8px 16px;
  border-radius: 5px;
  background-color: var(--primary);
  color: white;
  border: none;
  cursor: pointer;
}

.card {
  background-color: var(--card-bg);
  border-radius: var(--border-radius);
  box-shadow: var(--shadow);
  padding: 16px;
  margin: 15px;
}

.post-header {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.post-user-info {
  flex: 1;
  margin-left: 15px;
}

.post-user-name {
  font-weight: 600;
  font-size: 1.1rem;
  color: var(--text-dark);
}

.post-time {
  font-size: 0.85rem;
  color: var(--text-light);
}

.post-title {
  font-weight: 700;
  font-size: 1.25rem;
  color: var(--text-dark);
  margin-bottom: 10px;
}

.post-content {
  color: var(--text-medium);
  line-height: 1.8;
  font-size: 1.05rem;
}

.post-content p {
  margin-bottom: 10px;
}

/* 图片画廊样式 */
.image-gallery {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-top: 15px;
}

.image-item {
  width: 32%;
  height: 120px;
  border-radius: 8px;
  overflow: hidden;
}

.gallery-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  cursor: pointer;
  transition: transform 0.3s ease;
}

.gallery-image:hover {
  transform: scale(1.05);
}

.post-footer {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  gap: 25px;
  margin-top: 20px;
  padding-top: 15px;
  border-top: 1px solid var(--border-color);
}

.post-action {
  display: flex;
  align-items: center;
  font-size: 0.95rem;
  color: var(--text-light);
  gap: 5px;
  cursor: pointer;
}

.post-action:active {
  transform: scale(0.95);
}

.post-action .fas {
  font-size: 1.2rem;
}

.post-action .liked {
  color: #ff5000;
}

.post-action .star {
  color: #ffc107;
}

.comments-section {
  margin: 15px;
}

.section-title {
  font-weight: 700;
  font-size: 1.2rem;
  color: var(--text-dark);
  margin-bottom: 15px;
  display: flex;
  align-items: center;
  gap: 10px;
}

.comment-form {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}

.comment-input {
  flex: 1;
  padding: 10px 15px;
  border-radius: 20px;
  border: 1px solid var(--border-color);
  background-color: var(--card-bg);
  color: var(--text-dark);
}

.comment-input:focus {
  outline: none;
  border-color: var(--primary);
}

.comment-submit {
  padding: 10px 20px;
  border-radius: 20px;
  background-color: var(--primary);
  color: white;
  border: none;
  cursor: pointer;
  transition: background-color 0.3s;
}

.comment-submit:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

.comment-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.comment-item {
  display: flex;
  gap: 15px;
  padding-bottom: 20px;
  border-bottom: 1px solid #f0f0f0;
}

.comment-item:last-child {
  border-bottom: none;
  padding-bottom: 0;
}

.comment-avatar {
  width: 45px;
  height: 45px;
  border-radius: 50%;
  background-color: #f9f9f9;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #3A7BFF;
  font-size: 1.2rem;
  flex-shrink: 0;
}

.comment-content {
  flex: 1;
}

.comment-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
}

.comment-author {
  font-weight: 600;
  font-size: 1rem;
}

.comment-time {
  font-size: 0.85rem;
  color: #999999;
}

.comment-text {
  color: #666666;
  line-height: 1.6;
}

.comment-actions {
  display: flex;
  gap: 15px;
  margin-top: 10px;
}

.comment-action {
  display: flex;
  align-items: center;
  gap: 5px;
  font-size: 0.9rem;
  color: var(--text-light);
  cursor: pointer;
}

/* 楼中楼样式 */
.reply-form {
  display: flex;
  gap: 10px;
  margin-top: 10px;
}

.reply-input {
  flex: 1;
  padding: 8px 12px;
  border-radius: 18px;
  border: 1px solid var(--border-color);
  background-color: var(--card-bg);
  color: var(--text-dark);
  font-size: 0.9rem;
}

.reply-input:focus {
  outline: none;
  border-color: var(--primary);
}

.reply-submit {
  padding: 8px 16px;
  border-radius: 18px;
  background-color: var(--primary);
  color: white;
  border: none;
  cursor: pointer;
  font-size: 0.9rem;
}

.nested-comments {
  margin-top: 10px;
  padding-left: 20px;
  border-left: 2px solid #eee;
}

.nested-comment-item {
  display: flex;
  gap: 12px;
  padding: 10px 0;
  border-bottom: 1px solid #f5f5f5;
}

.nested-comment-item:last-child {
  border-bottom: none;
}

.nested-comment-avatar {
  width: 35px;
  height: 35px;
  border-radius: 50%;
  flex-shrink: 0;
}

.nested-comment-content {
  flex: 1;
}

.nested-comment-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 5px;
}

.nested-comment-author {
  font-weight: 500;
  font-size: 0.9rem;
}

.nested-comment-time {
  font-size: 0.8rem;
  color: #999;
}

.nested-comment-text {
  color: #666;
  font-size: 0.9rem;
  line-height: 1.5;
}

/* 图片预览样式 */
.image-preview-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.9);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;
  cursor: zoom-out;
}

.preview-container {
  position: relative;
  width: 90%;
  height: 90%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.preview-image {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
  cursor: default;
}

.preview-nav {
  position: absolute;
  width: 100%;
  display: flex;
  justify-content: space-between;
  padding: 0 20px;
}

.nav-btn {
  background-color: rgba(0, 0, 0, 0.5);
  color: white;
  border: none;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: background-color 0.3s;
}

.nav-btn:hover {
  background-color: rgba(0, 0, 0, 0.8);
}

.nav-btn:disabled {
  opacity: 0.3;
  cursor: not-allowed;
}

.preview-count {
  position: absolute;
  bottom: -30px;
  color: white;
  font-size: 1rem;
  background-color: rgba(0, 0, 0, 0.5);
  padding: 5px 10px;
  border-radius: 10px;
}

.success-message {
  background-color: #4CAF50;
  color: white;
  padding: 10px 15px;
  border-radius: 5px;
  margin-bottom: 15px;
  display: flex;
  align-items: center;
  gap: 8px;
}

</style>